package com.kungfuhacking.wristbandpro.login.presenter;

import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.base.view.HomeActivity;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.login.bean.LoginBean;
import com.kungfuhacking.wristbandpro.login.view.ILoginView;
import com.kungfuhacking.wristbandpro.mqtt.MqttConstant;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.CommonUtils;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import java.util.Set;

import io.reactivex.disposables.Disposable;

/**
 * 登录
 * Created by Aaron on 17/3/21.
 */

public class ILoginPresenter implements BasePresenter {

    private ILoginView iLoginView;

    public ILoginPresenter(ILoginView iLoginView) {
        this.iLoginView = iLoginView;
    }

    /**
     * 自动登录
     */
    public void autoLogin() {

        if (!TextUtils.isEmpty(iLoginView.getCacheUsername()) &&
                !TextUtils.isEmpty(iLoginView.getCachePassword())) {

            LogUtil.d(TAG, "自动登录了");

            iLoginView.setUsername(iLoginView.getCacheUsername());
            iLoginView.setPassword(Constant.WRISTBAND_PRO_CODE);

            login(iLoginView.getUsername(), iLoginView.getPassword());

        }

    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     */
    public void login(String username, String password) {

        if (TextUtils.isEmpty(username)) {
            iLoginView.showErr("请输入手机号");
            return;
        }

        if (username.length() != 11) {
            iLoginView.showErr("请输入正确的手机号码");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            iLoginView.showErr("请输入密码");
            return;
        }

        if (password.equals(Constant.WRISTBAND_PRO_CODE)) {
            password = iLoginView.getCachePassword();
        } else {
            password = CommonUtils.toMd5(password.getBytes());
        }

        loginIn(username, password);

    }

    private void loginIn(String username, String password) {

        JSONObject j = new JSONObject();

        j.put("phoneNum", username);
        j.put("pwd", password);

        RetrofitHttpUtil.getInstance().loginIn(new BaseNoTObserver<LoginBean>() {
            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
                iLoginView.showLoading("登录中...");
            }

            @Override
            public void onHandleSuccess(LoginBean loginBean) {
                iLoginView.hideLoading();

                saveUserInfo(loginBean);
            }

            @Override
            public void onHandleError(String message) {
                iLoginView.hideLoading();
                iLoginView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iLoginView.showErr(message);
                iLoginView.hideLoading();
                iLoginView.nextActivityWithSingleTask(LoginActivity.class);
            }

        }, new RequestBean().setData(j.toString()));

    }

    /**
     * 保存用户信息
     *
     * @param loginBean 用户信息
     */
    private void saveUserInfo(LoginBean loginBean) {

        iLoginView.getSp().edit().putBoolean(MqttConstant.INTERVAL_CONNET_MQTT, false).apply();

        SharedPreferences.Editor edit = iLoginView.getSp().edit();
        //用户信息
        edit.putString(Constant.USER_ID, loginBean.getData().getId());
        edit.putString(Constant.MOBILE, loginBean.getData().getMobile());
        edit.putString(MqttConstant.USERID, loginBean.getData().getMobile());
        edit.putString(Constant.NICKNAME, loginBean.getData().getNickName());
        edit.putString(Constant.USER_IMG, loginBean.getData().getUserImg());
        edit.putString(Constant.SEX, loginBean.getData().getSex());
        edit.putString(Constant.BIRTHDAY, loginBean.getData().getBirthDay());

        String token = loginBean.getToken().getToken();
        LogUtil.d(TAG, "token : " + token);
        edit.putString(Constant.TOKEN, token);
        //账号密码
//        edit.putString(Constant.MOBILE, iLoginView.getUsername());
        if (!Constant.WRISTBAND_PRO_CODE.equals(iLoginView.getPassword()))
            edit.putString(Constant.PASSWORD, CommonUtils.toMd5(iLoginView.getPassword().getBytes()));

        //保存 消息提醒
        Object readObj = CommonUtils.readObj(MqttConstant.REMAIND + iLoginView.getUsername());
        if (readObj != null) {
            Set<String> remaind = (Set<String>) readObj;
//            Log.d(TAG, "保存的不需要提醒的的消息" +   remaind.toString());
            edit.putStringSet(MqttConstant.REMAIND + iLoginView.getUsername(), remaind).apply();
        } else {
            Log.e(TAG, " readObj 为 空 ");
        }
        edit.apply();

        //进入主页
        iLoginView.nextActivity(HomeActivity.class);
//        iLoginView.nextActivityThenKill(HomeActivity.class);

    }

    private String TAG = getClass().getSimpleName();

    @Override
    public void clearRequest() {
//        LogUtil.d(TAG, " ~~~ 取消网络请求 ~~~ ");
        compositeDisposable.clear();
    }
}
